package ch2.tools;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;

/**
 * 类说明：演示CyclicBarrier用法,共4个子线程，他们全部完成工作后，交出自己结果，
 * 再被统一释放去做自己的事情，而交出的结果被另外的线程拿来拼接字符串
 */
public class UseCyclicBarrier {
    //子线程达到5就会执行await后面的代码,第二个参数可为空，就没有汇总线程
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new CollectThread());

    //存放线程工作结果的容器
    private static ConcurrentHashMap<String, Long> resultMap = new ConcurrentHashMap<>();


    public static void main(String[] args) {
        //相互等待的5个子线程
        for (int i = 0; i <= 4; i++) {
            Thread thread = new Thread(new SubThread());
            thread.start();
        }
    }

    //相互等待的子线程
    private static class SubThread implements Runnable {
        @Override
        public void run() {
            long id = Thread.currentThread().getId();
            resultMap.put(Thread.currentThread().getId() + "", id);
            try {
                Thread.sleep(1000 + id);
                System.out.println("子线程：Thread_" + id + " ....do something ");
                cyclicBarrier.await();
                Thread.sleep(1000 + id);
                System.out.println("子线程：Thread_" + id + " ....do its business ");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //汇总的任务
    private static class CollectThread implements Runnable {
        @Override
        public void run() {
            StringBuilder result = new StringBuilder();
            for (Map.Entry<String, Long> workResult : resultMap.entrySet()) {
                result.append("[").append(workResult.getValue()).append("]");
            }
            System.out.println("汇总线程：the result = " + result);
            System.out.println("汇总线程 do other business........");
        }
    }

}
